package com.extremelylargepackage;

import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;


public abstract class Engine 
{
	protected ThreadCallBack _thread;
	private StopWatch _clock;
	protected boolean _paused;
	protected boolean _initialized;

	public Engine(ThreadCallBack thread)
	{
		_thread = thread;
		_clock = new StopWatch();
	}
	
	/*
	 * Set up and start the engine.
	 */
	public void initialize()
	{
		onInitialize();
		_initialized = true;
		_paused = false;
		_clock.start();
	}
	
	protected abstract void onInitialize();
	/*
	 * Update engine.
	 */
	public void gameLogic()
	{
		if(!_paused && _initialized)
		{
			long interval = _clock.timeSinceLastLap();
			//Game simulation may break if the time step is too large.
			//If the frame rate is lower than 30 fps. Slow down the game speed.
			if(interval > 1000/30)
				interval = 1000/30;
			
			if(interval < 0)
			{
				//This should be impossibly since I changed form currentTimeMillis to nanoTime.
				//The check is here just in case.
				return;
			}
			
			_clock.lap();
			updateState(interval);
		}
	}
	
	protected abstract void updateState(long interval);
	
	public abstract void draw(Canvas c);
	
	public abstract void onTouch(MotionEvent event);
	
	public void setPaused(boolean paused)
	{
		_paused = paused;
		if(_paused)
			_clock.pause();
		else
			_clock.resume();
	}
	
	public boolean isPaused()
	{
		return _paused;
	}
	
	public long getElapsedTime()
	{
		return _clock.elapsedTime();
	}
}
